package com.appology.jokes;

import java.util.Random;
import java.util.List;
import java.util.ArrayList;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;

public class Joke {
	private static Joke instance = null;
	protected Joke(){
		generator = new Random();
	}
	public static Joke getInstance() {
	      if(instance == null) {
	         instance = new Joke();
	      }
	      return instance;
	   }
	public String getRandom(String name){
		if(name == null){
			name = "Chuck Norris";
		}
		int max = 1;
		int count = getCount();
		if(count >= 0){
			max = count;
		}
		int randomIndex = generator.nextInt(max);
        String myString = getJokeFromDB(randomIndex).replaceAll("TKname","<span class=\"name\">"+name.trim()+"</span>");
        
    	return myString;
	}
	
	private static Random generator;
	
	
	/**
	 * Adds the Chuck Norris Jokes to the DB
	 * @return No return value
	 */
	public void AddItemsToDB()
	{
		//Add all of the jokes to an arrayList that will be added to the Datastore
		ArrayList alist = new ArrayList();
	    alist.add("TKname is so cool, he gives <em>slurpies<em> brain freeze.");
		alist.add("TKname <strong><em>can</em></strong> believe it's not butter.");
		alist.add("TKname doesn't shave, he roundhouse kicks himself in the face.  The only thing hard enough to cut TKname is TKname.");
		alist.add("TKname is currently filing suit against NBC claiming that Law and Order are the respective trademarked names of his right and left legs.");
		alist.add("TKname can burn ants with a magnifying glass... <strong><em>at night!</em></strong>");
		alist.add("When the boogie man goes to bed at night, he checks his closet for TKname.");
		alist.add("Batman has TKname pajamas.");
		alist.add("The quickest way to a man's heart is TKname's fist.");
		alist.add("Chuck Norris dressed up as TKname for halloween, and even scared himself.");
		alist.add("When TKname does a pushup, he isn't pushing himself up, he's pushing the earth down.");
		alist.add("TKname's tears can cure cancer, it's too bad TKname has <em>never</em> cried.");
		alist.add("There is no such thing as thunder, only TKname's laughter.");
		alist.add("Why does the sun rise in the east? Because TKname is chasing it from the other side.");
		alist.add("Everyone knows the speed of light.  TKname knows the speed of <em>darkness</em>.");
		alist.add("It is believed that dinosaurs are extinct because of a giant meteor.  That is true if you want to call TKname a giant meteor");
		alist.add("TKname is set to star in the remake of the movie \"300\" except it will now be titled \"1\".");
		alist.add("Bears play dead when they are attacked by TKname.");
		alist.add("TKname can split the atom.  With his bare hands.");
		alist.add("Aliens do exist, but they know better than to invade the planet where TKname lives.");
		alist.add("TKname <strong><em>can</em></strong> handle the truth.");
		alist.add("TKname <strong><em>can</em></strong> eat just one Lays potato chip.");
		alist.add("Candyman is scared to look in the mirror and say TKname five times.");
		alist.add("TKname never tries. He just <em>does</em>.");
		alist.add("The Doctor has travelled as TKname's companion.");
		alist.add("People invented cars to get away from TKname.  Then they invented airplanes because they thought TKname couldn't fly.");
		alist.add("When TKname was kidnapped by aliens, he did expirements on them.");
		alist.add("TKname can punch a cyclops between the eye.");
		alist.add("TKname can drown a fish.");
		alist.add("The Earth may revolve around the Sun, but the Sun revolves around TKname.");
		alist.add("TKname always carries four methods of destruction: two arms and two legs.");
		alist.add("TKname is not politically correct.  He is just correct.  Always.");
		alist.add( "TKname never shocks his hand on the doorknob.  The doorknob gets shocked on TKname's hand.");
		alist.add("TKname can hit a home run with a bunt.");
		alist.add("TKname doesn't write books.  The words assemble themselves out of fear.");
		alist.add("TKname counted to infinity.  Twice.");
		alist.add("TKname does not hunt because the word hunting infers the possibility of failure. TKname goes killing.");
		alist.add("TKname has already been to Mars; That's why there are no signs of life there.");
		alist.add("In fine print on the last page of the Guinness Book of World Records it notes that all world records are held by TKname, and those listed in the book are simply the closest anyone else has ever gotten. ");
		alist.add("The chief export of TKname is <em>pain</em>.");
		alist.add("The Great Wall of China was originally created to keep TKname out. It failed misserably.");
		alist.add("TKname is a man of few words. TKname is not a man of few roundhouse kicks to the face.");
		alist.add("TKname knows where Carmen Sandiego is.");
		alist.add("China was once bordering the United States, until TKname roundhouse kicked it all the way through the Earth.");
	    alist.add("TKname is what Willis was talking about");
		alist.add("If you have five dollars and TKname has five dollars, TKname has more money than you.");
		alist.add("When TKname had surgery, the anesthesia was applied to the doctors.");
		alist.add("TKname once broke the land speed record on a bicycle that was missing its chain and the back tire.");
		alist.add("Time waits for no man.  Except TKname.");
		alist.add("TKname can touch MC Hammer." );
		alist.add("TKname ordered a Big Mac at Burger King, and got one." );		
		alist.add("If paper beats rock, rock beats scissors, and scissors beats paper, what beats all 3 at the same time? Answer: TKname. ");
		alist.add("TKname drinks napalm to quell his heartburn.");
		alist.add("If you want a list of TKname's enemies, just check the extinct species list. ");		
		alist.add( "TKname has never blinked in his entire life. <em><strong>Never</strong></em>. ");		
		alist.add("If Superman and The Flash were to race to the edge of space you know who would win? TKname. ");
		alist.add("In a fight between The Thing and The Hulk, the winner would be TKname.");
		alist.add( "TKname got a perfect score on his SATs, simply by writing TKname for every answer.");
		alist.add( "TKname doesn't cheat death. He wins fair and square.");
		alist.add("TKname can speak braille.");
		alist.add("TKname's calendar goes straight from March 31st to April 2nd; no one fools TKname.");
		alist.add("TKname does not sleep. He <em>waits</em>.");
		alist.add("TKname once won a game of Connect Four in 3 moves.");
		alist.add("TKname can delete the Recycling Bin.");
		alist.add("TKname can do a wheelie on a unicycle.");
		alist.add("TKname can squeeze orange juice out of a <em>lemon</em>.");
		alist.add("Once a cobra bit TKname's leg. After five days of excruciating pain, the cobra died.");
		alist.add("TKname died ten years ago, but the Grim Reaper can't get up the courage to tell him.");
		alist.add("TKname can slam revolving doors.");
		alist.add("Giraffes were created when TKname uppercutted a horse.");
		alist.add("Superman owns a pair of TKname pajamas.");
		alist.add("TKname doesn't read books. He stares them down until he gets the information he wants.");
		alist.add("TKname can kill two stones with one bird.");
		alist.add( "Death once had a near-TKname experience.");
		alist.add("TKname sleeps with a night light. Not because TKname is afraid of the dark, but the dark is afraid of TKname");
		alist.add("Bill Gates lives in constant fear that TKname's PC will crash.");
		alist.add("TKname is the only person on the planet that can kick you in the back of the face.");
		alist.add("Last year, TKname shot a 14 on an 18 hole golf course, falling short of his personal best by 2 strokes.");
		alist.add("TKname never retreats, he just attacks in the opposite direction.");
		alist.add("TKname has to maintain a concealed weapon license in all 50 states in order to legally wear pants.");
		alist.add("TKname can build a snowman out of rain.");
		alist.add("TKname once punched a man in the soul.");
		alist.add("TKname eats the core of an apple first.");
		alist.add("TKname plays russian roulette with a fully loded revolver... <em>and wins</em>.");
		alist.add("The only time TKname was wrong was when he thought he had made a mistake.");
		alist.add("When TKname enters a room, he doesn't turn the lights on, he turns the dark off.");
		alist.add("It is considered a great accomplishment to go down Niagara Falls in a wooden barrel. TKname can go up Niagara Falls in a cardboard box.");
		alist.add("TKname once bowled a 300. Without a ball. He wasn't even in a bowling alley.");
		alist.add("TKname knows the last digit of pi.");
		alist.add("Brett Favre can throw a football over 50 yards. TKname can throw Brett Favre <em>even further</em>.");
		alist.add("TKname can tie his shoes with his feet.");
		alist.add("The President has TKname on speed dial... <em>on the red phone</em>");
		alist.add("TKname is so fast he can start a fire by rubbing two ice cubes together.");
		alist.add("TKname is the reason why Waldo is hiding.");

			    
		//Create a key for the entity that will be added to the datastore
//	    Key jokeKey = KeyFactory.createKey("Jokes", "aJoke");

	
		/**
		 * Load all the jokes into the Google datastore
		 */
		for (int i=0; i< alist.size(); i++)
		{
			DatastoreService datastore =
				DatastoreServiceFactory.getDatastoreService();
			Entity joke = new Entity("Jokes", i+1);
		    joke.setProperty("content", alist.get(i));
		    //Use an aId so that we can guarantee that the id will 
		    //fall into our random number generator
		    //ID - is auto-incremented therefore can be problematic
		    joke.setProperty("aId", i+1);
			datastore.put(joke);	
		}
	}
	/**
	 * Counts the number of items in the DB
	 */
	public int getCount(){
		DatastoreService datastore =
			DatastoreServiceFactory.getDatastoreService();
		Query query = new Query("Jokes");
		return datastore.prepare(query).countEntities();
	}
	
	/**
	 * Actually gets the Joke from the datastore by the random number
	 */
	public String getJokeFromDB(int ranId)
	{
		
		DatastoreService datastore =  DatastoreServiceFactory.getDatastoreService();     
		 
	    Query query = new Query( "Jokes");
	    query.addFilter("aId", Query.FilterOperator.EQUAL, ranId);
	 
	    List<Entity> jokes  = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(1));  
        String answer = "";
	      if (jokes.isEmpty()) 
	      {
	    	  answer = "No jokes available.";
	      }
	      else
	      {
	    	  for (Entity joke : jokes) 
	          {        
	    		  answer =  joke.getProperty("content").toString();
	          }
	     }
	      return answer;
 	}
}
